// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/common/base/bigint_id_map.h>
#include <pollux/common/base/exceptions.h>

namespace kumo::pollux {
    void BigintIdMap::makeTable(int64_t capacity) {
        POLLUX_CHECK_LE(capacity, kMaxCapacity);
        byteSize_ = capacity * kEntrySize + kReadPadding;
        table_ = reinterpret_cast<char *>(pool_.allocate(byteSize_));
        memset(table_, 0, byteSize_);
        capacity_ = capacity;
        sizeMask_ = capacity_ - 1;
        limit_ = capacity_ * kEntrySize;
        maxEntries_ = capacity_ - capacity_ / 4;
    }

    void BigintIdMap::resize(int64_t newCapacity) {
        POLLUX_CHECK_LE(newCapacity, kMaxCapacity);

        auto oldCapacity = capacity_;
        auto oldTable = table_;
        auto oldByteSize = byteSize_;
        makeTable(newCapacity);
        for (auto i = 0; i < oldCapacity; ++i) {
            auto ptr = valuePtr(oldTable, i);
            if (*ptr == kEmptyMarker) {
                continue;
            }
            auto newIndex = indexOfEntry(*ptr);
            auto newPtr = valuePtr(table_, newIndex);
            while (*newPtr != kEmptyMarker) {
                newIndex = (newIndex + 1) & sizeMask_;
                newPtr = valuePtr(table_, newIndex);
            }
            *newPtr = *ptr;
            *idPtr(newPtr) = *idPtr(ptr);
        }
        pool_.free(oldTable, oldByteSize);
    }
} // namespace kumo::pollux
